package com.huluobo.a2109mvvmtiktok.login;

import androidx.lifecycle.Observer;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.blankj.utilcode.util.ToastUtils;
import com.huluobo.a2109mvvmtiktok.R;
import com.huluobo.a2109mvvmtiktok.databinding.ActivityLoginBinding;
import com.huluobo.a2109mvvmtiktok.register.RegisterActivity;
import com.huluobo.a2109mvvmtiktok.register.RegisterViewModel;
import com.huluobo.mvvm_base.bean.UserBeanResult;
import com.huluobo.mvvm_base.view.BaseMVVMActivity;

public class LoginActivity extends BaseMVVMActivity<ActivityLoginBinding, LoginViewModel> {

    @Override
    protected void initData() {
        //观察ViewModel中LiveData的值是否发生改变,如果改变,代表成功或者失败已经赋值
        viewModel.loginSuccess.observe(this, new Observer<UserBeanResult>() {
            @Override
            public void onChanged(UserBeanResult loginBeanResult) {
                if (loginBeanResult.getCode() == 200) {
                    ToastUtils.showLong("登录成功:" + loginBeanResult.getData().getUsername());
                } else {
                    ToastUtils.showLong("登录失败:" + loginBeanResult.getMessage());
                }
            }
        });

        viewModel.loginFailed.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                Log.i("TagA", "登录失败:" + s);
            }
        });
    }

    @Override
    protected void initView() {
        dataBinding.loginBtn.setOnClickListener(v -> {
            String username = dataBinding.loginEdUsername.getText().toString();
            String password = dataBinding.loginEdPassword.getText().toString();
            if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
                ToastUtils.showLong("请输入用户名或密码");
                return;
            }
            //验证用户名密码不为空,发起登录请求
            viewModel.login(username, password);
        });
        dataBinding.loginToRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    protected Class<LoginViewModel> getViewModel() {
        return LoginViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }
}